package com.fowo.api.sys.controller;

import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.fowo.api.common.model.R;
import com.fowo.api.common.util.DataUtils;
import com.fowo.api.sys.entity.SysTaskDataSource;
import com.fowo.api.sys.model.SysTaskDataSourceSearch;
import com.fowo.api.sys.service.SysTaskDataSourceService;
import io.swagger.v3.oas.annotations.Operation;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import java.util.List;

@RestController
@RequestMapping("/api/sys/task/ds")
public class SysTaskDataSourceController {
    @Resource
    private SysTaskDataSourceService sysTaskDataSourceService;

    @GetMapping("page")
    @Operation(summary = "分页搜索")
    public R<Page<SysTaskDataSource>> searchPage(SysTaskDataSourceSearch search) {
        final Page<SysTaskDataSource> sysTaskDataSourcePage = sysTaskDataSourceService.searchPage(search);
        DataUtils.desensitization(sysTaskDataSourcePage.getRecords());
        return R.data(sysTaskDataSourcePage);
    }

    @GetMapping
    @Operation(summary = "搜索")
    public R<List<SysTaskDataSource>> search(SysTaskDataSourceSearch search) {
        List<SysTaskDataSource> list = sysTaskDataSourceService.search(search);
        DataUtils.desensitization(list);
        return R.data(list);
    }

    @GetMapping("{id}")
    @Operation(summary = "详情")
    public R<SysTaskDataSource> getById(@PathVariable Long id) {
        return R.data(sysTaskDataSourceService.getById(id));
    }

    @PostMapping
    @Operation(summary = "新增")
    @PreAuthorize("@am.canAccess('sysTask')")
    public R<Long> create(@RequestBody @Validated SysTaskDataSource sysTaskDataSource) {
        if (sysTaskDataSourceService.create(sysTaskDataSource)) {
            return R.data(sysTaskDataSource.getId());
        }
        return R.fail("未知问题，未能创建成功");
    }

    @PutMapping
    @Operation(summary = "更新")
    public R update(@RequestBody @Validated SysTaskDataSource sysTaskDataSource) {
        return R.ok(() -> sysTaskDataSourceService.update(sysTaskDataSource));
    }

    @DeleteMapping("{id}")
    @Operation(summary = "删除")
    public R delete(@PathVariable Long id) {
        return R.ok(() -> sysTaskDataSourceService.delete(id));
    }
}
